﻿using System;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using WaterCloud.Code;
using SqlSugar;
using WaterCloud.DataBase;
using WaterCloud.Domain.AttendanceManagement;
using WaterCloud.Domain.RecruitmentManagement;
using WaterCloud.Domain.SystemOrganize;
using WaterCloud.Domain.SystemManage;
using static Serenity.Web.PropertyItemsScript;
using Newtonsoft.Json.Serialization;

namespace WaterCloud.Service.AttendanceManagement
{
    /// <summary>
    /// 创 建：超级管理员
    /// 日 期：2025-04-10 09:23
    /// 描 述：请假单服务类
    /// </summary>
    public class HolidayService : BaseService<HolidayEntity>, IDenpendency
    {
        public HolidayService(ISqlSugarClient context) : base(context)
        {
        }
        #region 获取数据
        public async Task<List<HolidayEntity>> GetList(string keyword = "")
        {
            var data = repository.IQueryable();
            if (!string.IsNullOrEmpty(keyword))
            {
                data = data.Where(a => a.F_UserNum.Contains(keyword)
                || a.F_RealName.Contains(keyword));
            }
            return await data.Where(a => a.F_DeleteMark == false).OrderBy(a => a.F_Id, OrderByType.Desc).ToListAsync();
        }
        public Boolean GetSumJson(string userid, string holidaytypeid, int day = 0)
        {   //工龄
            var listage = Db.Queryable<UserEntity>()

             .Where(it => it.F_Id == userid)//普通过滤
                                            //.Having(it => SqlFunc.AggregateCount(it.Id) > 0)//聚合函数过滤
             .Select(it => new
             {
                 workage = SqlFunc.DateDiff(DateType.Month, Convert.ToDateTime(it.F_Redate), DateTime.Now),
                 month = Convert.ToDateTime(it.F_Redate).Month
             }).ToList();

            if (listage.Count > 0)
            {
                var workage = listage[0].workage;
                var month = 12 - listage[0].month;
                //假期类型参数
                var hoilday = Db.Queryable<HolidaytypeEntity>().Where(a => a.F_Id == holidaytypeid).ToList()[0];
                var listparameter = Db.Queryable<HolidaytypeparameterEntity>().Where(a => a.F_HolidayTypeId == holidaytypeid).OrderBy(a => a.F_SortCode).ToList();
                Double days = 0;
                Double days1 = 0;
                Double daysed = 0;
                bool data = false;
                Double rateddays = 0;
                if (hoilday.F_WorkAge == true)
                {
                    for (int i = 0; i < listparameter.Count; i++)
                    {
                        var item = listparameter[i];
                        if (i >= 1)
                        {
                            var item1 = listparameter[i - 1];
                            rateddays = Convert.ToDouble(item1.F_RatedDays);
                        }

                        if (DateTime.Now.Month <= 2)
                        {
                            if (workage >= item.F_StartYear * 12 && workage < item.F_EndYear * 12)
                            {

                                if (workage <= item.F_StartYear * 12 + month)
                                {
                                    days1 = month * Convert.ToDouble(item.F_RatedDays) / 12;
                                    days = rateddays + days1 + Convert.ToDouble(item.F_RatedDays);
                                }

                                else
                                {
                                    days = Convert.ToDouble(item.F_RatedDays) * 2;
                                }
                                break;
                            }


                        }
                        else
                        {

                            if (workage >= item.F_StartYear * 12 && workage < item.F_EndYear * 12)
                            {

                                if (workage <= item.F_StartYear * 12 + month)
                                {
                                    days1 = month * Convert.ToDouble(item.F_RatedDays) / 12;
                                    days = rateddays + days1;
                                }

                                else
                                {
                                    days = Convert.ToDouble(item.F_RatedDays);
                                }
                                break;
                            }
                        }
                    }

                    //已请假天数


                    var hoildayed = Db.Queryable<HolidayEntity>()
                        .GroupBy(a => new { a.F_UserId })
                        .Where(a => (a.F_UserId == userid) && SqlFunc.DateDiff(DateType.Year, Convert.ToDateTime(a.F_CreatorTime), DateTime.Now) == (hoilday.F_Cycle - 1))
                        .Select(a => new { daysed = SqlFunc.AggregateSumNoNull(a.F_Days) })
                        .ToList();
                    if (hoildayed.Count > 0)
                    {

                        daysed = Convert.ToDouble(hoildayed[0].daysed);
                    }

                    if ((days - daysed - day) < 0)
                    {

                        data = true;
                    }
                }
             return data;
            }
            else {  return false; }


           
        }


        public async Task<List<HolidayEntity>> GetLookList(string keyword = "")
        {
            var query = repository.IQueryable().Where(a => a.F_DeleteMark == false);
            if (!string.IsNullOrEmpty(keyword))
            {
                //此处需修改
                query = query.Where(a => a.F_UserNum.Contains(keyword)
                || a.F_RealName.Contains(keyword));
            }
            //权限过滤
            query = GetDataPrivilege("a", "", query);
            return await query.OrderBy(a => a.F_Id, OrderByType.Desc).ToListAsync();
        }

        public async Task<List<HolidayEntity>> GetLookList(SoulPage<HolidayEntity> pagination, string keyword = "", string id = "", string hoilday = "")
        {
            var query = repository.Db.Queryable<HolidayEntity,UserEntity, OrganizeEntity, RoleEntity, HolidaytypeEntity>((a, b, c, d,e) => new JoinQueryInfos(
           JoinType.Left, a.F_UserId == b.F_Id,
                JoinType.Left, b.F_OrganizeId == c.F_Id,
            JoinType.Left, b.F_DutyId == d.F_Id,
             JoinType.Left, a.F_HolidayTypeId == e.F_Id
            ))
            .Select((a, b, c, d,e) => new HolidayEntity
            {
                F_Id = a.F_Id.SelectAll(),
                F_OrganizeName = c.F_FullName,
                F_DutyName = d.F_FullName,
                F_HolidayTypeName = e.F_FullName,

            }).MergeTable();
            if (!string.IsNullOrEmpty(keyword))
            {
                query = query.Where(a => a.F_UserNum.Contains(keyword)
                || a.F_RealName.Contains(keyword));
            }
            if (!string.IsNullOrEmpty(id))
            {
                query = query.Where(a => a.F_Id == id);
            }
            //权限过滤
            query = GetDataPrivilege("a", "", query);
            return await query.ToPageListAsync(pagination);
        }


        public async Task<HolidayEntity> GetForm(string keyValue)
        {
            var data = await repository.FindEntity(keyValue);
            return data;
        }
        #endregion

        public async Task<HolidayEntity> GetLookForm(string keyValue)
        {
            var data = await repository.FindEntity(keyValue);
           
            return GetFieldsFilterData(data);
        }

        #region 提交数据
        public async Task SubmitForm(HolidayEntity entity, string keyValue)
        {
            if (string.IsNullOrEmpty(keyValue))
            {
                //初始值添加
                entity.F_DeleteMark = false;
                entity.Create();
                await repository.Insert(entity);
            }
            else
            {
                //此处需修改
                entity.Modify(keyValue);
                await repository.Update(entity);
            }
        }

        public async Task DeleteForm(string keyValue)
        {
            var ids = keyValue.Split(',');
            await repository.Delete(a => ids.Contains(a.F_Id.ToString()));
        }
        public async Task ReviewForm(string keyValue, bool b)
        {
            var ids = keyValue.Split(',');
           
                await repository.Update(a => ids.Contains(a.F_Id), a => new HolidayEntity
                {
                    F_EnabledMark = b,
               

                });

        }
        #endregion

    }
}
